package com.emns.web.mobile;

import java.util.Calendar;
import java.util.Date;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.emns.pojo.User;
import com.emns.pojo.Validate;
import com.emns.service.user.UserService;
import com.emns.web.mobile.entity.UserMessage;

@Controller
@RequestMapping(value = "/userMobile")
public class UserMobileController {
	@Autowired
	UserService us;

	@RequestMapping(value = "/login")
	public String login(Model model, @RequestParam(required = false) String uid) {
		UserMessage usermess = new UserMessage();
		Validate v = us.queryValidate();
		Date date = new Date();
		if (uid == null) {
			String s = UUID.randomUUID().toString();

			String uuid = s.substring(0, 8) + s.substring(9, 13)
					+ s.substring(14, 18) + s.substring(19, 23)
					+ s.substring(24);
			User user = new User();
			user.setLogincode(uuid);

			user.setStartdate(date);

			user.setEnddate(getEndDate(date, v.getMonth()));
			int result = us.addUserByMobile(user);
			if (result > 0) {
				usermess.setUserid(uuid);
				usermess.setState(0);
				usermess.setStateMessage("可用");
				model.addAttribute("info", usermess);
				model.addAttribute("errorCode", 0);
				return "";
			} else {
				model.addAttribute("errorMessage", "程序登陆错误");
				model.addAttribute("errorCode", 1);
			}
		} else {

			User u = us.getUserForMobile(uid);

			if (u != null) {
				if (date.getTime() < u.getEnddate().getTime()) {
					usermess.setUserid(u.getLogincode());
					usermess.setState(0);
					usermess.setStateMessage("可用");
					model.addAttribute("info", usermess);
					model.addAttribute("errorCode", 0);
					return "";
				} else {
					usermess.setUserid(u.getLogincode());
					usermess.setState(1);
					usermess.setStateMessage("程序已过期");
					model.addAttribute("info", usermess);
					model.addAttribute("errorCode", 0);
					return "";
				}
			} else {
				model.addAttribute("errorMessage", "无此用户");
				model.addAttribute("errorCode", 2);
			}

		}
		return "";
	}

	/**
	 * 计算技术日期
	 * 
	 * @param d1
	 * @param month
	 * @return
	 */
	public Date getEndDate(Date d1, int month) {
		Calendar c = Calendar.getInstance();
		c.setTime(d1);
		c.add(Calendar.MONTH, month);

		return c.getTime();

	}
}
